﻿CREATE PROCEDURE [dbo].[Text_Insert]
	@userId UNIQUEIDENTIFIER
	,	@beforeTextId BIGINT
	, @hashTag NVARCHAR(128)
	, @tag NVARCHAR(32)
	, @value NVARCHAR(MAX)
AS
BEGIN
	DECLARE @order INT, @chapterId UNIQUEIDENTIFIER

	SET @hashTag = LOWER(@hashTag)
	BEGIN TRY
		BEGIN TRANSACTION

			IF @beforeTextId > 0
			BEGIN
				SELECT @chapterId = t.[ChapterId], @order = t.[Order]
				FROM [dbo].[text_Text] AS t
				INNER JOIN [dbo].[text_Chapter] AS c ON t.[ChapterId] = c.[ChapterId]
				WHERE c.[HashTag] = @hashTag AND (@beforeTextId = 0 OR t.[TextId] = @beforeTextId)
			END
			ELSE
			BEGIN
				SELECT @chapterId = [ChapterId]
				FROM [dbo].[text_Chapter]
				WHERE [HashTag] = @hashTag
			END

			IF @chapterId IS NULL OR [dbo].[IsViewUnpublished](@userId) <> 1
			BEGIN
				ROLLBACK TRANSACTION
				RETURN
			END

			IF @beforeTextId > 0
			BEGIN
				UPDATE [dbo].[text_Text]
					 SET [Order] = [Order] + 1
				 WHERE [ChapterId] = @chapterId AND [Order] >= @order
			END
			ELSE
			BEGIN
				SELECT @order = MAX([Order])
				FROM [dbo].[text_Text]
				WHERE [ChapterId] = @chapterId

				SET @order = ISNULL(@order, -1) + 1
			END

			INSERT INTO [dbo].[text_Text]
									([ChapterId]
									,[Value]
									,[Order]
									,[Tag]
									,[IsPublic])
			VALUES
								(@chapterId
								,@value
								,@order
								,@tag
								,[dbo].[IsTagPublic](@tag))

			UPDATE [dbo].[text_Chapter]
			SET [UpdateDate] = GETUTCDATE()
			WHERE [ChapterId] = @chapterId
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT	@ErrorMessage = ERROR_MESSAGE(),
						@ErrorSeverity = ERROR_SEVERITY(),
						@ErrorState = ERROR_STATE();

		RAISERROR (
								@ErrorMessage, -- Message text.
								@ErrorSeverity, -- Severity.
								@ErrorState -- State.
							);

	END CATCH

END